package com.example.springcloud.storage.controller;

import com.example.springcloud.storage.result.Result;
import com.example.springcloud.storage.service.StorageService;
import com.example.springcloud.storage.service.tcc.StorageTCCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 库存控制器
 */
@Slf4j
@RestController
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService storageService;

    @Autowired
    private StorageTCCService storageTCCService;

    /**
     * 扣减库存 - AT 模式
     */
    @PostMapping("/deduct")
    public Result<Void> deduct(@RequestParam("productId") Long productId,
                               @RequestParam("count") Integer count) {
        log.info("收到扣减库存请求 - AT 模式: productId={}, count={}", productId, count);
        // ✅ 分布式事务：不要捕获异常，让异常向上抛出触发全局回滚
        storageService.deduct(productId, count);
        return Result.success();
    }

    /**
     * 扣减库存 - TCC Try
     */
    @PostMapping("/deduct/tcc/try")
    public Result<Void> deductTccTry(@RequestParam("productId") Long productId,
                                     @RequestParam("count") Integer count) {
        log.info("收到扣减库存请求 - TCC Try: productId={}, count={}", productId, count);
        try {
            storageTCCService.tryDeduct(productId, count);
            return Result.success();
        } catch (Exception e) {
            log.error("TCC Try 扣减库存失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 扣减库存 - XA 模式
     */
    @PostMapping("/deduct/xa")
    public Result<Void> deductXa(@RequestParam("productId") Long productId,
                                  @RequestParam("count") Integer count) {
        log.info("收到扣减库存请求 - XA 模式: productId={}, count={}", productId, count);
        // ✅ 分布式事务：不要捕获异常，让异常向上抛出触发全局回滚
        storageService.deductXa(productId, count);
        return Result.success();
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("Storage Service is running");
    }
}

